package com.gjs.reviewtree.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gjs.reviewtree.bean.Review;
import com.gjs.reviewtree.controller.vo.AddReviewReqVO;
import com.gjs.reviewtree.dao.ReviewMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ReviewServiceImpl implements ReviewService {

    @Resource
    private ReviewMapper reviewMapper;

    @Override
    public IPage<Review> list(Long parentId, Integer pageNum, Integer pageSize) {
        IPage<Review> reviewIPage = reviewMapper.selectPage(Page.of(pageNum, pageSize),
                Wrappers.lambdaQuery(new Review().setParentId(parentId)).isNull(parentId == null , Review::getParentId).orderByDesc(Review::getCreateDate));
        return reviewIPage;
    }

    @Override
    @Transactional
    public Review add(AddReviewReqVO reqVO) {

        if (reqVO.getParentId() != null) {
            Review parent = reviewMapper.selectById(reqVO.getParentId());
            Assert.notNull(parent, "不存在的评论, ID=" + reqVO.getParentId());
            reviewMapper.updateSubCountById(parent.getId(), 1);
        }
        Review review = new Review().setParentId(reqVO.getParentId()).setContent(reqVO.getContent())
                .setCreateDate(new Date().getTime()).setSubCount(0);

        reviewMapper.insert(review);

        return review;
    }

    @Override
    public boolean remove(Long id) {
        Review old = reviewMapper.selectById(id);
        Assert.notNull(old, "不存在的评论, ID=" + id);
        if (old.getParentId() != null) {
            reviewMapper.updateSubCountById(old.getParentId(), -1);
        }
        return reviewMapper.deleteById(id) > 0;
    }
}
